import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  env: {},
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  permissionRoles: [],
  channels: [],
  gameId: 0
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ENV: (state, env) => {
    state.env = env
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PERMISSIONROLES: (state, permissionRoles) => {
    state.permissionRoles = permissionRoles
  },
  SET_CHANNELS: (state, channels) => {
    state.channels = channels
  }
  // SET_GAMEID: (state, gameId) => {
  //   state.gameId = gameId
  // }
}

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    // const { username, password, captchakey, captcha } = userInfo
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('验证失败，请重新登录！')
        }
        const { roles, permission_roles, name, avatar, channels, env } = data

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        // if (channels || channels.length > 0) {
        //   commit('SET_GAMEID', channels[0]['id'])
        // }

        commit('SET_ROLES', roles)
        commit('SET_PERMISSIONROLES', permission_roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_CHANNELS', channels)
        commit('SET_ENV', env)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONROLES', [])
        commit('SET_CHANNELS', [])
        commit('SET_GAMEID', 0)
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_PERMISSIONROLES', [])
      commit('SET_CHANNELS', [])
      commit('SET_GAMEID', 0)
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const userInfo = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', userInfo, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  },

  // 更改游戏id
  changeGameId({ commit }, param) {
    commit('SET_GAMEID', param)
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

